//
//  ZCHomeController.swift
//  weibo
//
//  Created by 张城 on 16/7/19.
//  Copyright © 2016年 张城. All rights reserved.
//

import UIKit
import SnapKit

private let ZCHomeCellId = "ZCHomeCell"

class ZCHomeController: ZCBaseController {
    
    lazy var homeViewModel: ZCHomeViewModel = ZCHomeViewModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !islogon {
            bgview?.setupVisiterView(nil, imgName: nil)
            return
        }
        getloadData()
        setupdataSourse()
     
    }
    
    func getloadData() {
        homeViewModel.homeLoadData(indicatorView.isAnimating()) { (isSuc, count) in
            
            self.indicatorView.stopAnimating()
            self.refreshview.endRefresh()
            
            if !isSuc {
                print("失败")
                return
            }
            //            print("成功")
            
            self.tableView.reloadData()
            
            if count >= 0 {
                
                self.setShowLabelAnim(count)
            }
            
//            self.showDataLabel.text = "\(count)"
        }

    }
    
    
    func setShowLabelAnim(count: Int) {
        
        if showDataLabel.hidden == false {
            return
        }
        
        showDataLabel.hidden = false
        
        var content: String = ""
        
        if count == 0 {
            content = "已是最新数据"
        }else{
            content = "更新了\(count)条数据"
        }
        
        showDataLabel.text = content
        
        UIView.animateWithDuration(0.2, animations: { 
            self.showDataLabel.transform = CGAffineTransformMakeTranslation(0, 35)
            
            }) { (_) in
            
                UIView.animateWithDuration(0.2, delay: 1, options: [], animations: { 
                    
                    self.showDataLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) in
                        
                        self.showDataLabel.hidden = true
                })
                
        }
        
    }
    
    
    
    
    func setupdataSourse() {
        tableView.dataSource = self
        tableView.delegate  = self
        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = .None
        tableView.backgroundColor = RGB(233, green: 233, blue: 233)
        tableView.registerClass(ZCHomeCell.self, forCellReuseIdentifier: ZCHomeCellId)
        
        tableView.tableFooterView = indicatorView
        tableView.addSubview(refreshview)
        
        navigationController?.view.insertSubview(showDataLabel, belowSubview: (navigationController?.navigationBar)!)
        
        refreshview.addTarget(self, action: #selector(ZCHomeController.perforeRefresh), forControlEvents: .ValueChanged)
        
    }
    
    func perforeRefresh(){
        
        getloadData()
    }
    
    private lazy var indicatorView: UIActivityIndicatorView = {
       let indi = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
        indi.color = UIColor.greenColor()
        return indi
    }()
    private lazy var refreshview: refresh = refresh()
    
    private lazy var showDataLabel: UILabel = {
       let label = UILabel(textColor: UIColor.whiteColor(), textFont: 14)
        label.frame = CGRectMake(0, 64 - 35, SCREENW, 35)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = .Center
        label.hidden = true
        return label
    }()
}

extension ZCHomeController : UITableViewDataSource , UITableViewDelegate{
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.dataArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(ZCHomeCellId, forIndexPath: indexPath) as! ZCHomeCell
        cell.homeCellViewModel = homeViewModel.dataArray[indexPath.row]
        return cell
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath){
        
        if indexPath.row == homeViewModel.dataArray.count - 1 && !indicatorView.isAnimating(){
            
            indicatorView.startAnimating()
            getloadData()
        }
        
    }
}


class ZCHomeCell: UITableViewCell {
    
    var toolBarBottomConstraint: Constraint?
    
    
    
    
    var homeCellViewModel: ZCHomeCellViewModel? {
        didSet{
            
            originateView.homeCellViewModel = homeCellViewModel
            
            toolBarView.homeCellViewModel = homeCellViewModel
            
            let result = homeCellViewModel?.homeModel?.retweeted_status
            
            
            self.toolBarBottomConstraint?.uninstall()
            
            if result == nil {
                
                toolBarView.snp_updateConstraints(closure: { (make) in
                    
                    self.toolBarBottomConstraint = make.top.equalTo(originateView.snp_bottom).constraint
                    
                })
                relayView.hidden = true
            }else{
                relayView.homeCellViewModel = homeCellViewModel
                
                toolBarView.snp_updateConstraints(closure: { (make) in
                    
                    self.toolBarBottomConstraint = make.top.equalTo(relayView.snp_bottom).constraint
                    
                })
                
                relayView.hidden = false

            }
            
            
        }
    }
    
    override var frame: CGRect{
        didSet{
            var newFrame = frame
            newFrame.origin.x += 10
            newFrame.size.width -= 20
//            newFrame.origin.y += 10
//            newFrame.size.height -= 10
            super.frame = newFrame
        }
    }
//
    
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = UIColor.clearColor()
        self.selectionStyle = .None
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupUI() {
        contentView.addSubview(originateView)
        contentView.addSubview(relayView)
        contentView.addSubview(toolBarView)
        
        originateView.snp_makeConstraints { (make) in
            make.leading.trailing.equalTo(contentView)
            make.top.equalTo(contentView).offset(10)
//            make.height.equalTo(170)
        }
        
        relayView.snp_makeConstraints { (make) in
            make.top.equalTo(originateView.snp_bottom)
            make.leading.trailing.equalTo(contentView)
//            make.height.equalTo(170)
        }
        
        toolBarView.snp_makeConstraints { (make) in
            self.toolBarBottomConstraint = make.top.equalTo(relayView.snp_bottom).constraint
            make.leading.trailing.equalTo(contentView)
            make.height.equalTo(35)
        }
//        
        self.contentView.snp_makeConstraints { (make) in
            make.leading.trailing.top.equalTo(self)
            make.bottom.equalTo(toolBarView.snp_bottom)
            
           // MARK:-- 如果在这里设置contentView的高度和cell的高度一样,就会出现约束冲突.
            // 但同时具有想要的 分隔的效果
//            make.height.equalTo(self)
        }
    }
    
    
    private lazy var originateView:ZCOriginateView = ZCOriginateView()
    private lazy var relayView: ZCRelayView = ZCRelayView()
    private lazy var toolBarView: ZCToolBarView = ZCToolBarView()
    
    
    
}









